package com.after.saas.common.utils;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.after.saas.common.constants.Constants;
import com.after.saas.common.constants.ErrorCodeEnum;
import com.after.saas.common.constants.JwtEnum;
import com.after.saas.common.exception.BizException;
import com.after.saas.common.model.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Optional;

/**
 * 当前登录用户工具
 *
 * @author hjchen
 * @date 2021-5-7
 */
public class UserUtil {

    Logger log = LoggerFactory.getLogger(UserUtil.class);

    private final RedisTemplate<String,Object> redisTemplate;

    @Value("${jwt.encode.secret}")
    private String secret;

    public UserUtil(RedisTemplate<String,Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 获取当前用户登录来源
     *
     * @return
     */
    public String getLoginSource() {
        return RequestUtil.getLoginRequestHeaderInfo(Constants.USER_LOGIN_SOURCE);
    }


    /**
     * 判断当前用户是否已登录
     *
     * @return userId
     */
    public boolean isUserLogin() {
        try {
            String loginToken = getLoginToken();
            return StrUtil.isNotBlank(loginToken) && JwtUtil.isTokenExpired(loginToken, secret);
        } catch (Exception e) {
            log.error("登录已过期,e={}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取登录用户信息
     *
     * @return UserVO
     */
    public UserVO getUserInfo() throws BizException {
        UserVO userVo = new UserVO();
        try {
            String loginToken = getLoginToken();
            String userId = JwtUtil.getUserIdFromToken(loginToken, secret);
            userVo.setId(userId);
            final String redisKey = LoginUtil.getRedisCacheLoginUserKey(userId);
            userVo = (UserVO) Optional.ofNullable(RedisUtil.getObject(redisTemplate, redisKey)).orElse(userVo);
        } catch (Exception e) {
            log.error("errorMsg {}", e.getMessage());
        }
        return userVo;
    }

    /**
     * 获取用户权限信息
     *
     * @return List<String>
     */
    public List<String> getUserPermissions(String userId) throws BizException {
        final String redisKey = LoginUtil.getRedisCacheUserPermissionKey(userId);
        return RedisUtil.lGetAll(redisTemplate, redisKey);
    }

    /**
     * 获取用户角色信息
     *
     * @return List<String>
     */
    public List<String> getUserRoles(String userId) throws BizException {
        return RedisUtil.lGetAll(redisTemplate, LoginUtil.getRedisCacheUserRoleKey(userId));
    }

    /**
     * 获取登录用户信息(抛出异常)
     *
     * @return UserVO
     */
    public UserVO getLoginUser() {
        String loginToken = getLoginToken();
        if (StrUtil.isEmpty(loginToken)) {
            log.info("Token为空:{}", loginToken);
            throw new BizException(ErrorCodeEnum.ACCESS_TOKEN_EMPTY);
        }
        String userId = JwtUtil.getUserIdFromToken(loginToken, secret);
        String redisKey = LoginUtil.getRedisCacheLoginUserKey(userId);
        UserVO UserVo = (UserVO) RedisUtil.getObject(redisTemplate, redisKey);
        if (ObjectUtil.isEmpty(UserVo)) {
            throw new BizException(ErrorCodeEnum.LOGOUT);
        }
        return UserVo;
    }

    /**
     * 获取登录token
     *
     * @return
     */
    public String getLoginToken() {
        return RequestUtil.getLoginRequestHeaderInfo(JwtEnum.WEB_FRONT.getTokenName());
    }

}
